package com.sangananitsolution.fragments;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.PeriodFormat;
import org.joda.time.format.PeriodFormatter;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import LoadImgfromUrl.ImageLoader;
import Utiliypackage.UilityClassFroTime;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.sangananitsolution.database.FavouirteItemCRUD;
import com.sangananitsolution.gogoproject.R;

public class MySearch_NearBy extends Fragment {
	int count = 0;
	double latitute, longitute;
	ArrayList<String> description = new ArrayList<String>();
	ArrayList<String> suburb = new ArrayList<String>();
	ArrayList<String> startdate = new ArrayList<String>();
	ArrayList<String> startime = new ArrayList<String>();
	ArrayList<String> finishtime = new ArrayList<String>();
	ArrayList<String> productImagesarray = new ArrayList<String>();
	ArrayList<String> productID = new ArrayList<String>();
	ArrayList<String> garageSaleTitle = new ArrayList<String>();
	ArrayList<String> oneOrTwoDaySale = new ArrayList<String>();
	ArrayList<String> unitStreeNo = new ArrayList<String>();
	ArrayList<String> streeName = new ArrayList<String>();
	ArrayList<String> city = new ArrayList<String>();
	ArrayList<String> state = new ArrayList<String>();

	ArrayList<String> postCodearray = new ArrayList<String>();
	ArrayList<String> earlyBirdMessage = new ArrayList<String>();
	ArrayList<String> badWeatherMessage = new ArrayList<String>();
	ArrayList<String> goodsTypearray = new ArrayList<String>();
	ArrayList<String> currentUser = new ArrayList<String>();
	ArrayList<String> longitude = new ArrayList<String>();
	ArrayList<String> latitude = new ArrayList<String>();

	public MySearch_NearBy(double longitute, double latitute) {
		this.latitute = latitute;
		this.longitute = longitute;

	}

	int id = 0;
	ListView listView;

	@Override
	public void onAttach(Activity activity) {

		new MysearchLocationnearByAPi().execute();

		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.mysearchproduct, container, false);
		listView = (ListView) view.findViewById(R.id.listviewmyserachProdct);

		CustomAdapter singlayoutforrow = new CustomAdapter(getActivity(),
				suburb, description, startdate, startime, finishtime);
		listView.setAdapter(singlayoutforrow);

		return view;
	}

	private class MysearchLocationnearByAPi extends
			AsyncTask<String, String, String> {

		private ProgressDialog pDialog;
		private final String URL = "http://garagesalesagogo.com.au/ProductService.asmx?op=SearchProducts1";
		private final String SOAP_ACTION = "http://tempuri.org/SearchProducts";
		private String TAG = "PGGURU";

		@Override
		protected String doInBackground(String... params) {
			Log.i(TAG, "I am in doInBackground");
			SoapObject searchProducts = null;
			SoapObject locationobj = null;
			SoapObject criteriaobj = null;

			searchProducts = new SoapObject("http://tempuri.org/",
					"SearchProducts");
			criteriaobj = new SoapObject("http://tempuri.org/", "criteria");

			locationobj = new SoapObject("http://tempuri.org/", "Location");
			locationobj.addProperty("Longitude", String.valueOf(longitute));
			locationobj.addProperty("Latitude", String.valueOf(latitute));
			locationobj.addProperty("Miles", "100");

			criteriaobj.addSoapObject(locationobj);
			searchProducts.addSoapObject(criteriaobj);

			// Create envelope
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.dotNet = true;
			// Set output SOAP object
			envelope.setOutputSoapObject(searchProducts);
			envelope.implicitTypes = true;
			// Create HTTP call object
			HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

			SoapObject searchProductsResponse = null;
			SoapObject searchProductsResult = null;
			SoapObject productDetails = null;
			SoapObject productImagesURL = null;

			SoapObject location = null;

			try {
				// Invole web service
				androidHttpTransport.call(SOAP_ACTION, envelope);
				// Get the response
				try {
					searchProductsResponse = (SoapObject) envelope.bodyIn;
				} catch (Exception exception) {
					Toast.makeText(getActivity(), "Tosat", 1000).show();
				}

				for (int i = 0; i < searchProductsResponse.getPropertyCount(); i++) {

					searchProductsResult = (SoapObject) searchProductsResponse
							.getProperty(i);

					for (int j = 0; j < searchProductsResult.getPropertyCount(); j++) {

						productDetails = (SoapObject) searchProductsResult
								.getProperty(j);

						String startdatevalue = (productDetails
								.getPropertyAsString("StartDate"));

						String starttimevalue = productDetails
								.getPropertyAsString("SaleStartTime");

						
						
				//		UilityClassFroTime uilityClassFroTime=new UilityClassFroTime(startdatevalue, starttimevalue);
						String successvalue =	new UilityClassFroTime(startdatevalue, starttimevalue).testForeligbleEntry();

					/*	String successvalue = testForeligbleEntry(
								startdatevalue, starttimevalue);*/

						{

							if (Integer.parseInt(successvalue) > 0) {
								description.add(productDetails
										.getPropertyAsString("Description"));
								suburb.add(productDetails
										.getPropertyAsString("Suburb"));

								try {
									productImagesURL = (SoapObject) productDetails
											.getProperty("ProductImagesURL");
									productImagesarray.add(productImagesURL
											.getPropertyAsString("string"));

								} catch (Exception e) {

									productImagesarray
											.add("~/ProductImages/2015215234459_323.png;");
								

								}

								startdate.add(productDetails
										.getPropertyAsString("StartDate"));
								startime.add(productDetails
										.getPropertyAsString("SaleStartTime"));
								finishtime.add(productDetails
										.getPropertyAsString("SaleFinishTime"));
								productID.add(productDetails
										.getPropertyAsString("ProductId"));
								garageSaleTitle
										.add(productDetails
												.getPropertyAsString("GarageSaleTitle"));
								oneOrTwoDaySale
										.add(productDetails
												.getPropertyAsString("OneOrTwoDaySale"));
								unitStreeNo.add(productDetails
										.getPropertyAsString("UnitStreeNo"));
								streeName.add(productDetails
										.getPropertyAsString("StreeName"));
								city.add(productDetails
										.getPropertyAsString("City"));
								state.add(productDetails
										.getPropertyAsString("State"));
								postCodearray.add(productDetails
										.getPropertyAsString("PostCode"));
								earlyBirdMessage
										.add(productDetails
												.getPropertyAsString("EarlyBirdMessage"));
								badWeatherMessage
										.add(productDetails
												.getPropertyAsString("BadWeatherMessage"));
								goodsTypearray.add(productDetails
										.getPropertyAsString("GoodsType"));

								currentUser.add(productDetails
										.getPropertyAsString("CurrentUser"));

								try {
									location = (SoapObject) productDetails
											.getProperty("Location");

									latitude.add(location
											.getPropertyAsString("Longitude"));
									longitude.add(location
											.getPropertyAsString("Latitude"));
								} catch (Exception e) {
									e.printStackTrace();
								}

							}

						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

	/*	public String testForeligbleEntry(String startdatevalue,
				String starttimevalue) {

			// finding the system current time and date of system
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
			Date date = new Date();
			String currentDate = sdf.format(date).toString();

			// getting minutes and hours from server
			String str = starttimevalue;
			int hours = 0, minutes = 0;
			DateFormat formatters = new SimpleDateFormat("h:mm a");
			Date dates;
			try {
				dates = formatters.parse(str);

				hours = dates.getHours();
				minutes = dates.getMinutes();
			} catch (ParseException e1) {

				e1.printStackTrace();
			}

			String salesStartDate = startdatevalue + " " + hours + ":"
					+ minutes;

			DateTimeZone timeZone = DateTimeZone.forID("America/Montreal");

			DateTimeFormatter formatter = DateTimeFormat.forPattern(
					"MM/dd/yyyy HH:mm").withZone(timeZone);

			DateTime dateTimeStart = formatter.parseDateTime(currentDate);
			DateTime dateTimeStop = formatter.parseDateTime(salesStartDate);
			Period period = new Period(dateTimeStart, dateTimeStop);
			PeriodFormatter periodFormatter = PeriodFormat.getDefault();
			String output = periodFormatter.print(period);

			// getremainingsalestime(output,finishtimemain);

			String splitdatetime[] = output.split("and");

			for (int i = 0; i < splitdatetime.length; i++)
				splitdatetime[i] = splitdatetime[i].trim();

			String result = "", tagvalue = "";

			for (int i = 0; i < splitdatetime.length; i++) {
				String datetime = splitdatetime[i];
				String[] timePosNegativesplit = datetime.split(",");
				String timePosNegative = timePosNegativesplit[0];
				String[] diftime = timePosNegative.split(" ");
				String dtime = diftime[0];

				String tag = diftime[1];
				if ((tag.equals("day")) && (Integer.parseInt(dtime) > 0)) {

					result = dtime;
					break;

				}

			}
			return result;

		}*/

		@Override
		protected void onPreExecute() {
			Log.i(TAG, "I am in onPreExecute");
			// Showing progress dialog

			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Please wait for match List...");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected void onPostExecute(String result) {
			if (pDialog.isShowing()) {

				pDialog.dismiss();

			}

			CustomAdapter singlayoutforrow = new CustomAdapter(getActivity(),
					suburb, description, startdate, startime, finishtime);
			listView.setAdapter(singlayoutforrow);
			super.onPostExecute(result);

		}

	}

	class CustomAdapter extends ArrayAdapter<String> {
		int[] images;
		String[] text;
		Context context1;
		ArrayList<String> dsecription;
		ArrayList<String> suburb;
		ArrayList<String> statdate;
		ArrayList<String> starttime;
		ArrayList<String> finishtimemain;

		public CustomAdapter(Context context, ArrayList<String> dse,
				ArrayList<String> sub, ArrayList<String> startdate,
				ArrayList<String> startimr, ArrayList<String> finshtime) {

			super(context, R.layout.singlerowlayout, R.id.txtsuburb, dse);

			this.dsecription = dse;
			this.context1 = context;
			this.suburb = sub;
			this.statdate = startdate;
			this.starttime = startimr;
			this.finishtimemain = finshtime;
		}

		@SuppressLint("ViewHolder")
		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			LayoutInflater inflater = (LayoutInflater) context1
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View view = inflater.inflate(R.layout.singlerowlayout,
					parent, false);

			view.findViewById(R.id.bttoaddfavoirte).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							// change the color of button to yellow if add to
							// favorite

							if (count == 0) {

								// add the data to db

								String longitut = null, latitute = null;
								try {
									longitut = longitude.get(position);
									latitute = latitude.get(position);
								} catch (Exception e) {
									// handle exception
									latitute = null;
									longitut = null;

								}
								FavouirteItemCRUD userInfoCRUD = new FavouirteItemCRUD(
										getActivity());
								userInfoCRUD.insertAllData(
										productImagesarray.get(position),
										garageSaleTitle.get(position),
										startdate.get(position),
										oneOrTwoDaySale.get(position),
										startime.get(position),
										finishtime.get(position),
										unitStreeNo.get(position),
										streeName.get(position),
										suburb.get(position),
										city.get(position),
										state.get(position),
										postCodearray.get(position),
										dsecription.get(position),
										earlyBirdMessage.get(position),
										badWeatherMessage.get(position),
										goodsTypearray.get(position),
										currentUser.get(position), longitut,
										latitute, productID.get(position));

								count = 1;
								view.findViewById(R.id.bttoaddfavoirte)
										.setBackgroundResource(
												R.drawable.delatefromdbbotton);
							} else {

								FavouirteItemCRUD userInfoCRUD = new FavouirteItemCRUD(
										getActivity());
								userInfoCRUD.deleteAllData(productID
										.get(position));

								count = 0;
								view.findViewById(R.id.bttoaddfavoirte)
										.setBackgroundResource(
												R.drawable.starnoselected);

							}

						}
					}

			);

			String setremain = setTime(starttime.get(position),
					statdate.get(position), finishtimemain.get(position));

			String image_url;
			ImageView imageView = (ImageView) view
					.findViewById(R.id.imageproduct);

			try {
				// Image url
				image_url = "http://garagesalesagogo.com.au//"
						+ productImagesarray.get(position).replace("~/", "");

			} catch (Exception e) {
				image_url = "http://garagesalesagogo.com.au//ProductImages/201522017214_986.png";

			}

			int loader = R.drawable.ic_launcher;
			ImageLoader imageLoader = new ImageLoader(getActivity());

			imageLoader.DisplayImage(image_url, loader, imageView);

			TextView textView = (TextView) view.findViewById(R.id.txtsuburb);

			TextView textView2 = (TextView) view
					.findViewById(R.id.txtdiscription);

			textView.setText(suburb.get(position));
			textView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// open the view in new page

					android.app.FragmentManager fragmentManager = getFragmentManager();
					android.app.FragmentTransaction fragmentTransaction = fragmentManager
							.beginTransaction();

					fragmentTransaction
							.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

					fragmentTransaction.addToBackStack(null);

					String longitut = null, latitute = null;
					try {
						longitut = longitude.get(position);
						latitute = latitude.get(position);
					} catch (Exception e) {
						// handle exception
						latitute = null;
						longitut = null;

					}
					fragmentTransaction
							.replace(
									R.id.mainfragmentlayout,
									new MySearch_SearchOption_OnSubmit_ItemClick(
											getActivity(), dsecription
													.get(position), suburb
													.get(position),
											productImagesarray.get(position),
											startdate.get(position), startime
													.get(position), finishtime
													.get(position), productID
													.get(position),
											garageSaleTitle.get(position),
											oneOrTwoDaySale.get(position),
											unitStreeNo.get(position),
											streeName.get(position), city
													.get(position), state
													.get(position),
											postCodearray.get(position),
											earlyBirdMessage.get(position),
											badWeatherMessage.get(position),
											goodsTypearray.get(position),
											currentUser.get(position),
											longitut, latitute,productImagesarray));
					fragmentTransaction.commit();

				}
			});
			textView2.setText(dsecription.get(position));

			textView2.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// open the view in new page
					/*
					 * Toast.makeText(getActivity(), "hello" + position,
					 * Toast.LENGTH_LONG).show();
					 */
					android.app.FragmentManager fragmentManager = getFragmentManager();
					android.app.FragmentTransaction fragmentTransaction = fragmentManager
							.beginTransaction();

					fragmentTransaction
							.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

					fragmentTransaction.addToBackStack(null);
					String longitut = null, latitute = null;
					try {
						longitut = longitude.get(position);
						latitute = latitude.get(position);
					} catch (Exception e) {
						// shandle exception
						latitute = null;
						longitut = null;

					}
					fragmentTransaction
							.replace(
									R.id.mainfragmentlayout,
									new MySearch_SearchOption_OnSubmit_ItemClick(
											getActivity(), dsecription
													.get(position), suburb
													.get(position),
											productImagesarray.get(position),
											startdate.get(position), startime
													.get(position), finishtime
													.get(position), productID
													.get(position),
											garageSaleTitle.get(position),
											oneOrTwoDaySale.get(position),
											unitStreeNo.get(position),
											streeName.get(position), city
													.get(position), state
													.get(position),
											postCodearray.get(position),
											earlyBirdMessage.get(position),
											badWeatherMessage.get(position),
											goodsTypearray.get(position),
											currentUser.get(position),
											longitut, latitute,productImagesarray));
					fragmentTransaction.commit();

				}
			});

			return view;
		}
	}

	public String setTime(String startTime, String startDate,
			String finishtimemain) {

		// finding the system current time and date of system
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
		Date date = new Date();
		String currentDate = sdf.format(date).toString();

		// getting minutes and hours from server
		String str = startTime;
		int hours = 0, minutes = 0;
		DateFormat formatters = new SimpleDateFormat("h:mm a");
		Date dates;
		try {
			dates = formatters.parse(str);

			hours = dates.getHours();
			minutes = dates.getMinutes();
		} catch (ParseException e1) {

			e1.printStackTrace();
		}

		String salesStartDate = startDate + " " + hours + ":" + minutes;

		DateTimeZone timeZone = DateTimeZone.forID("America/Montreal");

		DateTimeFormatter formatter = DateTimeFormat.forPattern(
				"MM/dd/yyyy HH:mm").withZone(timeZone);

		DateTime dateTimeStart = formatter.parseDateTime(currentDate);
		DateTime dateTimeStop = formatter.parseDateTime(salesStartDate);
		Period period = new Period(dateTimeStart, dateTimeStop);
		PeriodFormatter periodFormatter = PeriodFormat.getDefault();
		String output = periodFormatter.print(period);

		// getremainingsalestime(output,finishtimemain);

		String splitdatetime[] = output.split("and");

		for (int i = 0; i < splitdatetime.length; i++)
			splitdatetime[i] = splitdatetime[i].trim();

		String result = "", tagvalue = "";

		for (int i = 0; i < splitdatetime.length; i++) {
			String datetime = splitdatetime[i];
			String[] timePosNegativesplit = datetime.split(",");
			String timePosNegative = timePosNegativesplit[0];
			String[] diftime = timePosNegative.split(" ");
			String dtime = diftime[0];

			String setremaing;
			if (Integer.parseInt(dtime) < 0) {

				result = "Go Go";

				break;
			}

			String tag = diftime[1];
			if (tag.equals("hours")) {
				tagvalue = "h";

			} else if (tag.equals("day"))

			{

				tagvalue = "d";

			}

			else if (tag.equals("week")) {
				tagvalue = "w";

			} else {

				tagvalue = "m";
			}

			result = result + " " + dtime + tagvalue;

		}

		// setremaing=dtime+"h"+" "+dtimes+"m";

		return result;

	}

}
